import { Component, Vue } from 'vue-property-decorator';
import user_axios from '@axios/user';
import ws_axios from '@axios/websocket';
import ws from '@ws';
import { FriendInfo, User } from '@/assets/js/entity/user';
import { SystemMsg } from '@/assets/js/entity/system_msg';
import { PrivateMsg } from '@/assets/js/entity/chat';

@Component
export class LoginBox extends Vue {

    /** 账号（用户名/电子邮箱/电话号码） */
    private token: string = '';

    /** 密码 */
    private passwd: string = '';

    /** 存储账号出现的问题 */
    private tokenCheck: Array<string> = [];
    
    /** 存储密码出现的问题 */
    private passwdCheck: Array<string> = [];

    /**
     * 在账号文本框失去焦点时被调用, 
     * 检查账号是否正确,
     * 不正确的信息将被记入 tokenCheck
     */
    public checkToken(): void {
        this.tokenCheck = [];
        if (this.token.isEmpty()) {
            this.tokenCheck.push('请输入您的登录账号');
        }
        if (this.token.isInvalid()) {
            this.tokenCheck.push('不能包含^%&\',;=?$\"等非法字符');
        }
    }

    /**
     * 在密码文本框失去焦点时被调用,
     * 检查密码是否正确,
     * 不正确的信息将被记入 passwdCheck
     */
    private checkPasswd(): void {
        this.passwdCheck = [];
        if (this.passwd.length < 8) {
            this.passwdCheck.push('至少包含8个字符');
        }
        if (this.passwd.isPassword()) {
            this.passwdCheck.push('必须包含大小写字母和数字的组合');
        }
    }

    /**
     * 判断是否能登录
     * 需要账号框、密码框里面都没有错误提示
     */
    private canLogin(): boolean {
        return  this.passwdCheck.length != 0 ||
                this.tokenCheck.length != 0;
    }

    /**
     * 登录
     * 首先判断账号类型, 将账号和密码加密之后进行请求
     */
    private doLogin(): void {
        let loginInfo: any = {};
        if (this.token.isEmail()) {
            loginInfo.email = this.token.encrypt();
        } else if (this.token.isTelephone()) {
            loginInfo.tel = this.token.encrypt();
        } else {
            loginInfo.name = this.token.encrypt();
        }
        loginInfo.password = this.passwd.encrypt();
        user_axios.base.login(loginInfo).then((res: User) => {
            this.$store.commit('setMe', res);
            ws.init();
            ws_axios.system.readSystemMsg(res.id, true).then((msgList: Array<SystemMsg>) => {
                this.$store.commit('addAllSystemMsg', msgList);
            });
            ws_axios.private.readPrivateMsg(res.id, true).then((msgList: Array<PrivateMsg>) => {
                this.$store.commit('addAllPrivateMsg', msgList);
            })
            user_axios.friend.queryMyFriends(res.id).then((friends: Array<FriendInfo>) => {
                this.$store.commit('addAllFriendInfo', friends);
            })
            this.$router.replace('/');
        })
    }

}